<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="GridFShttps://docs.mongodb.com/manual/core/gridfs/index.html#use-gridfs GridFS 用于存储和恢复那些超过16M（BSON文件限制）的文件(如：图片、音频、视频等)。 GridFS 也是文件存储的一种方式，但是它是存储在MonoDB的集合中。 GridFS 可以更好的存储大于16M的文件。 GridFS 会将大文件对象分割成">
<meta name="keywords" content="Mongo">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB4-GridFS、Capped Collections、索引与查询计划">
<meta property="og:url" content="http://www.saily.top/2018/01/07/mongo4/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="GridFShttps://docs.mongodb.com/manual/core/gridfs/index.html#use-gridfs GridFS 用于存储和恢复那些超过16M（BSON文件限制）的文件(如：图片、音频、视频等)。 GridFS 也是文件存储的一种方式，但是它是存储在MonoDB的集合中。 GridFS 可以更好的存储大于16M的文件。 GridFS 会将大文件对象分割成">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://docs.mongodb.com/manual/_images/index-for-sort.bakedsvg.svg">
<meta property="og:image" content="https://docs.mongodb.com/manual/_images/index-compound-key.bakedsvg.svg">
<meta property="og:updated_time" content="2018-01-27T03:24:45.363Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB4-GridFS、Capped Collections、索引与查询计划">
<meta name="twitter:description" content="GridFShttps://docs.mongodb.com/manual/core/gridfs/index.html#use-gridfs GridFS 用于存储和恢复那些超过16M（BSON文件限制）的文件(如：图片、音频、视频等)。 GridFS 也是文件存储的一种方式，但是它是存储在MonoDB的集合中。 GridFS 可以更好的存储大于16M的文件。 GridFS 会将大文件对象分割成">
<meta name="twitter:image" content="https://docs.mongodb.com/manual/_images/index-for-sort.bakedsvg.svg">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/01/07/mongo4/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>MongoDB4-GridFS、Capped Collections、索引与查询计划 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/01/07/mongo4/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MongoDB4-GridFS、Capped Collections、索引与查询计划
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-07T10:13:24+08:00">1月 7 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Mongo/" itemprop="url" rel="index"><span itemprop="name">Mongo</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="GridFS"><a href="#GridFS" class="headerlink" title="GridFS"></a>GridFS</h1><p><a href="https://docs.mongodb.com/manual/core/gridfs/index.html#use-gridfs" target="_blank" rel="noopener">https://docs.mongodb.com/manual/core/gridfs/index.html#use-gridfs</a></p>
<p>GridFS 用于存储和恢复那些超过16M（BSON文件限制）的文件(如：图片、音频、视频等)。</p>
<p>GridFS 也是文件存储的一种方式，但是它是存储在MonoDB的集合中。</p>
<p>GridFS 可以更好的存储大于16M的文件。</p>
<p>GridFS 会将大文件对象分割成多个小的chunk(文件片段),一般为256k/个,每个chunk将作为MongoDB的一个文档(document)被存储在chunks集合中。</p>
<p>GridFS 用两个集合来存储一个文件：fs.files与fs.chunks。</p>
<p>每个文件的实际内容被存在chunks(二进制数据)中,和文件有关的meta数据(filename,content_type,还有用户自定义的属性)将会被存在files集合中。<br><a id="more"></a><br>以下是简单的 fs.files 集合文档：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">   <span class="string">"filename"</span>: <span class="string">"test.txt"</span>,</span><br><span class="line">   <span class="string">"chunkSize"</span>: NumberInt(<span class="number">261120</span>),</span><br><span class="line">   <span class="string">"uploadDate"</span>: ISODate(<span class="string">"2014-04-13T11:32:33.557Z"</span>),</span><br><span class="line">   <span class="string">"md5"</span>: <span class="string">"7b762939321e146569b07f72c62cca4f"</span>,</span><br><span class="line">   <span class="string">"length"</span>: NumberInt(<span class="number">646</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以下是简单的 fs.chunks 集合文档：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">   <span class="string">"files_id"</span>: ObjectId(<span class="string">"534a75d19f54bfec8a2fe44b"</span>),</span><br><span class="line">   <span class="string">"n"</span>: NumberInt(<span class="number">0</span>),</span><br><span class="line">   <span class="string">"data"</span>: <span class="string">"Mongo Binary Data"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="mongofiles"><a href="#mongofiles" class="headerlink" title="mongofiles"></a>mongofiles</h2><p>mongodb提供了一个<code>mongofiles</code>命令来管理GridFS。</p>
<p><code>mongofiles &lt;options&gt; &lt;commands&gt; &lt;filename&gt;</code></p>
<p>它的参数在文档都有详细的解释</p>
<p><a href="https://docs.mongodb.com/manual/reference/program/mongofiles/index.html" target="_blank" rel="noopener">https://docs.mongodb.com/manual/reference/program/mongofiles/index.html</a></p>
<h3 id="上传"><a href="#上传" class="headerlink" title="上传"></a>上传</h3><p>上传一个东西测试一下，<code>-d</code>指定数据库，<code>-l</code>指定要上传的文件地址</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">~ mongofiles -d mytest -l /Users/xiaomai/Desktop/WXWork_2.4.5.213.dmg put wxwork.dmg</span><br><span class="line">2018-01-07T11:59:51.831+0800	connected to: localhost</span><br><span class="line">added file: wxwork.dmg</span><br></pre></td></tr></table></figure>
<p>可以查一下fs.files和fs.chunks这两个数据库</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.fs.files.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca8"</span>), <span class="string">"chunkSize"</span> : <span class="number">261120</span>, <span class="string">"uploadDate"</span> : ISODate(<span class="string">"2018-01-07T03:59:52.285Z"</span>), <span class="string">"length"</span> : <span class="number">22230276</span>, <span class="string">"md5"</span> : <span class="string">"b0c833f7325342227ddff80e03462000"</span>, <span class="string">"filename"</span> : <span class="string">"wxwork.dmg"</span> &#125;</span><br></pre></td></tr></table></figure>
<p>由于chunks里保存的二进制数据，特别多，所以查询的时候把data字段给忽略一下</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.fs.chunks.find(&#123;&#125;,&#123;data:0&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca9"</span>), <span class="string">"files_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca8"</span>), <span class="string">"n"</span> : 0 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8ecaa"</span>), <span class="string">"files_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca8"</span>), <span class="string">"n"</span> : 1 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8ecab"</span>), <span class="string">"files_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca8"</span>), <span class="string">"n"</span> : 2 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8ecac"</span>), <span class="string">"files_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca8"</span>), <span class="string">"n"</span> : 3 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8ecad"</span>), <span class="string">"files_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca8"</span>), <span class="string">"n"</span> : 4 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8ecae"</span>), <span class="string">"files_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca8"</span>), <span class="string">"n"</span> : 5 &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8ecaf"</span>), <span class="string">"files_id"</span> : ObjectId(<span class="string">"5a519b37e59cf07feeb8eca8"</span>), <span class="string">"n"</span> : 6 &#125;</span><br><span class="line">Type <span class="string">"it"</span> <span class="keyword">for</span> more</span><br></pre></td></tr></table></figure>
<p>当然，这个数据也不少，chunkSize是261120，除以1024，一块是255k。</p>
<h3 id="搜索"><a href="#搜索" class="headerlink" title="搜索"></a>搜索</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">➜  ~ mongofiles -d mytest search w</span><br><span class="line">2018-01-07T12:44:41.433+0800	connected to: localhost</span><br><span class="line">wxwork.dmg	22230276</span><br></pre></td></tr></table></figure>
<h3 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">➜  ~ mongofiles -d mytest delete wxwork.dmg </span><br><span class="line">2018-01-07T12:45:46.190+0800	connected to: localhost</span><br><span class="line">successfully deleted all instances of <span class="string">'wxwork.dmg'</span> from GridFS</span><br></pre></td></tr></table></figure>
<h1 id="Capped-Collections"><a href="#Capped-Collections" class="headerlink" title="Capped Collections"></a>Capped Collections</h1><p><a href="https://docs.mongodb.com/manual/core/capped-collections/index.html" target="_blank" rel="noopener">https://docs.mongodb.com/manual/core/capped-collections/index.html</a></p>
<blockquote>
<p>Capped collections are fixed-size collections that support high-throughput operations that insert and retrieve documents based on insertion order. Capped collections work in a way similar to circular buffers: once a collection fills its allocated space, it makes room for new documents by overwriting the oldest documents in the collection.</p>
</blockquote>
<p>MongoDB 固定集合（Capped Collections）是性能出色且有着固定大小的集合，对于大小固定，我们可以想象其就像一个环形队列，当集合空间用完后，再插入的元素就会覆盖最初始的头部的元素！</p>
<p>一般只新增不更新，更新要求更新后的集合大小不能超过之前的大小，否则会出错。</p>
<p>2.2版本之后，_id就自带索引了，在2.2之前，需要显式的在_id字段上创建索引。</p>
<h2 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h2><p><a href="https://docs.mongodb.com/manual/core/capped-collections/index.html#create-a-capped-collection" target="_blank" rel="noopener">https://docs.mongodb.com/manual/core/capped-collections/index.html#create-a-capped-collection</a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.createCollection(<span class="string">"log"</span>,&#123;<span class="attr">capped</span>:<span class="literal">true</span>,<span class="attr">size</span>:<span class="number">1000</span>&#125;)</span><br><span class="line">&#123; <span class="string">"ok"</span> : <span class="number">1</span> &#125;</span><br></pre></td></tr></table></figure>
<p>mongodb会先判断size的大小是否超过限制，然后再判断集合里文档的数量是否超过了max设定的值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.createCollection(<span class="string">"log"</span>, &#123; <span class="attr">capped</span> : <span class="literal">true</span>, <span class="attr">size</span> : <span class="number">100</span>, <span class="attr">max</span> : <span class="number">2</span> &#125; )</span><br><span class="line">&gt; db.log.insert(&#123;<span class="attr">count</span>:<span class="number">1</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.log.insert(&#123;<span class="attr">count</span>:<span class="number">2</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.log.insert(&#123;<span class="attr">count</span>:<span class="number">3</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.log.insert(&#123;<span class="attr">count</span>:<span class="number">4</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.log.insert(&#123;<span class="attr">count</span>:<span class="number">5</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.log.find(&#123;&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51aec1fef2eb6e769d4f36"</span>), <span class="string">"count"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51aec5fef2eb6e769d4f37"</span>), <span class="string">"count"</span> : <span class="number">5</span> &#125;</span><br></pre></td></tr></table></figure>
<p>这也印证了之前的说法，在超过2条以后，新插入的会覆盖最早的记录。</p>
<h2 id="查询"><a href="#查询" class="headerlink" title="查询"></a>查询</h2><p><a href="https://docs.mongodb.com/manual/core/capped-collections/index.html#query-a-capped-collection" target="_blank" rel="noopener">https://docs.mongodb.com/manual/core/capped-collections/index.html#query-a-capped-collection</a></p>
<p>如果没有指定排序，mongodb会保证查询的结果就是插入的顺序。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.log.find().sort(&#123;<span class="attr">$natural</span>: <span class="number">-1</span>&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51aec5fef2eb6e769d4f37"</span>), <span class="string">"count"</span> : <span class="number">5</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51aec1fef2eb6e769d4f36"</span>), <span class="string">"count"</span> : <span class="number">4</span> &#125;</span><br></pre></td></tr></table></figure>
<p>判断一个集合是否是capped：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.log.isCapped();</span><br><span class="line"><span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>转换一个普通的集合成固定集合：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.runCommand(&#123;<span class="string">'convertToCapped'</span>: <span class="string">'hello'</span>, <span class="attr">size</span>:<span class="number">1000</span>&#125;);</span><br><span class="line">&#123; <span class="string">"ok"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&gt; db.hello.isCapped()</span><br><span class="line"><span class="literal">true</span></span><br></pre></td></tr></table></figure>
<h1 id="索引与查询计划"><a href="#索引与查询计划" class="headerlink" title="索引与查询计划"></a>索引与查询计划</h1><p>索引通常能够极大的提高查询的效率，如果没有索引，MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。</p>
<p>这种扫描全集合的查询效率是非常低的，特别在处理大量的数据时，查询可以要花费几十秒甚至几分钟，这对网站的性能是非常致命的。</p>
<p>索引是特殊的数据结构，索引存储在一个易于遍历读取的数据集合中，索引是对数据库表中一列或多列的值进行排序的一种结构。</p>
<p><img src="https://docs.mongodb.com/manual/_images/index-for-sort.bakedsvg.svg" alt=""></p>
<p>mongodb默认会给每一个集合的<code>_id</code>字段上创建一个索引。</p>
<h2 id="创建索引"><a href="#创建索引" class="headerlink" title="创建索引"></a>创建索引</h2><p>数据准备：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.insert(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>, <span class="attr">age</span>:<span class="number">10</span>&#125;);</span><br><span class="line">&gt; db.myindex.insert(&#123;<span class="attr">name</span>:<span class="string">'lisi'</span>, <span class="attr">age</span>:<span class="number">20</span>&#125;);</span><br><span class="line">&gt; db.myindex.insert(&#123;<span class="attr">name</span>:<span class="string">'wangwu'</span>, <span class="attr">age</span>:<span class="number">14</span>&#125;);</span><br><span class="line">&gt; db.myindex.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51c3d1a893e40faf1670cb"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">10</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51c3e5a893e40faf1670cc"</span>), <span class="string">"name"</span> : <span class="string">"lisi"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51c404a893e40faf1670cd"</span>), <span class="string">"name"</span> : <span class="string">"wangwu"</span>, <span class="string">"age"</span> : <span class="number">14</span> &#125;</span><br></pre></td></tr></table></figure>
<p>查询一下现有索引：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.getIndexes();</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"_id_"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p>给age和name创建一个索引，1和-1表示升序还是降序：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.createIndex(&#123;<span class="attr">age</span>:<span class="number">1</span>&#125;);</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"createdCollectionAutomatically"</span> : <span class="literal">false</span>,</span><br><span class="line">	<span class="string">"numIndexesBefore"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"numIndexesAfter"</span> : <span class="number">2</span>,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">&gt; db.myindex.createIndex(&#123;<span class="attr">name</span>:<span class="number">1</span>&#125;);</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"createdCollectionAutomatically"</span> : <span class="literal">false</span>,</span><br><span class="line">	<span class="string">"numIndexesBefore"</span> : <span class="number">2</span>,</span><br><span class="line">	<span class="string">"numIndexesAfter"</span> : <span class="number">3</span>,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">&gt; db.myindex.getIndexes();</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"_id_"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"age"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"age_1"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"name"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"name_1"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p>给索引起个别名，并将创建索引的操作后台运行，意思不会阻塞当前的线程。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.createIndex(&#123;<span class="attr">name</span>:<span class="number">1</span>&#125;, &#123;<span class="attr">name</span>:<span class="string">'helloIndex'</span>, <span class="attr">background</span>:<span class="number">1</span>&#125;)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"createdCollectionAutomatically"</span> : <span class="literal">false</span>,</span><br><span class="line">	<span class="string">"numIndexesBefore"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"numIndexesAfter"</span> : <span class="number">2</span>,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">&gt; db.myindex.getIndexes();</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"_id_"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"name"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"helloIndex"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span>,</span><br><span class="line">		<span class="string">"background"</span> : <span class="number">1</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h2 id="删除索引"><a href="#删除索引" class="headerlink" title="删除索引"></a>删除索引</h2><p>删除单个：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.dropIndex(&#123;<span class="attr">name</span>:<span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure>
<p>删除所有：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.dropIndexes();</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"nIndexesWas"</span> : <span class="number">2</span>,</span><br><span class="line">	<span class="string">"msg"</span> : <span class="string">"non-_id indexes dropped for collection"</span>,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">&gt; db.myindex.getIndexes();</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"_id_"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h2 id="唯一索引"><a href="#唯一索引" class="headerlink" title="唯一索引"></a>唯一索引</h2><p>指定unique参数创建一个唯一索引，插入字段有相同的值，会执行失败。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.dropIndex(&#123;<span class="attr">name</span>:<span class="number">1</span>&#125;);</span><br><span class="line">&#123; <span class="string">"nIndexesWas"</span> : <span class="number">2</span>, <span class="string">"ok"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&gt; db.myindex.createIndex(&#123;<span class="attr">name</span>:<span class="number">1</span>&#125;, &#123;<span class="attr">unique</span>:<span class="number">1</span>&#125;)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"createdCollectionAutomatically"</span> : <span class="literal">false</span>,</span><br><span class="line">	<span class="string">"numIndexesBefore"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"numIndexesAfter"</span> : <span class="number">2</span>,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">&gt; db.myindex.getIndexes();</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"_id_"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"unique"</span> : <span class="literal">true</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"name"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"name_1"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br><span class="line">&gt; db.myindex.insert(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>,<span class="attr">age</span>:<span class="number">2</span>&#125;);</span><br><span class="line">WriteResult(&#123;</span><br><span class="line">	<span class="string">"nInserted"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"writeError"</span> : &#123;</span><br><span class="line">		<span class="string">"code"</span> : <span class="number">11000</span>,</span><br><span class="line">		<span class="string">"errmsg"</span> : <span class="string">"E11000 duplicate key error collection: test.myindex index: name_1 dup key: &#123; : \"zhangsan\" &#125;"</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="查询计划"><a href="#查询计划" class="headerlink" title="查询计划"></a>查询计划</h2><p>虽然设置了索引，我们在做查询的时候，可能并不是很确定到底用到了索引没有。跟传统sql一样，mongo提供了查询计划来检测。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.find(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>&#125;).explain();</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"queryPlanner"</span> : &#123;</span><br><span class="line">		<span class="string">"plannerVersion"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"namespace"</span> : <span class="string">"test.myindex"</span>,</span><br><span class="line">		<span class="string">"indexFilterSet"</span> : <span class="literal">false</span>,</span><br><span class="line">		<span class="string">"parsedQuery"</span> : &#123;</span><br><span class="line">			<span class="string">"name"</span> : &#123;</span><br><span class="line">				<span class="string">"$eq"</span> : <span class="string">"zhangsan"</span></span><br><span class="line">			&#125;</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"winningPlan"</span> : &#123;</span><br><span class="line">			<span class="string">"stage"</span> : <span class="string">"FETCH"</span>,</span><br><span class="line">			<span class="string">"inputStage"</span> : &#123;</span><br><span class="line">				<span class="string">"stage"</span> : <span class="string">"IXSCAN"</span>,</span><br><span class="line">				<span class="string">"keyPattern"</span> : &#123;</span><br><span class="line">					<span class="string">"name"</span> : <span class="number">1</span></span><br><span class="line">				&#125;,</span><br><span class="line">				<span class="string">"indexName"</span> : <span class="string">"name_1"</span>,</span><br><span class="line">				<span class="string">"isMultiKey"</span> : <span class="literal">false</span>,</span><br><span class="line">				<span class="string">"multiKeyPaths"</span> : &#123;</span><br><span class="line">					<span class="string">"name"</span> : [ ]</span><br><span class="line">				&#125;,</span><br><span class="line">				<span class="string">"isUnique"</span> : <span class="literal">true</span>,</span><br><span class="line">				<span class="string">"isSparse"</span> : <span class="literal">false</span>,</span><br><span class="line">				<span class="string">"isPartial"</span> : <span class="literal">false</span>,</span><br><span class="line">				<span class="string">"indexVersion"</span> : <span class="number">2</span>,</span><br><span class="line">				<span class="string">"direction"</span> : <span class="string">"forward"</span>,</span><br><span class="line">				<span class="string">"indexBounds"</span> : &#123;</span><br><span class="line">					<span class="string">"name"</span> : [</span><br><span class="line">						<span class="string">"[\"zhangsan\", \"zhangsan\"]"</span></span><br><span class="line">					]</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"rejectedPlans"</span> : [ ]</span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"serverInfo"</span> : &#123;</span><br><span class="line">		<span class="string">"host"</span> : <span class="string">"2dd4d04418b1"</span>,</span><br><span class="line">		<span class="string">"port"</span> : <span class="number">27017</span>,</span><br><span class="line">		<span class="string">"version"</span> : <span class="string">"3.6.0"</span>,</span><br><span class="line">		<span class="string">"gitVersion"</span> : <span class="string">"a57d8e71e6998a2d0afde7edc11bd23e5661c915"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>主要是看<code>indexBounds</code>，可以确定是用了name的索引。</p>
<p>因为之前把age上的索引删除了，所以查询age&gt;5的数据，则没有用到索引。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.find(&#123;<span class="attr">age</span>:&#123;<span class="attr">$gt</span>:<span class="number">5</span>&#125;&#125;).explain();</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"queryPlanner"</span> : &#123;</span><br><span class="line">		<span class="string">"plannerVersion"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"namespace"</span> : <span class="string">"test.myindex"</span>,</span><br><span class="line">		<span class="string">"indexFilterSet"</span> : <span class="literal">false</span>,</span><br><span class="line">		<span class="string">"parsedQuery"</span> : &#123;</span><br><span class="line">			<span class="string">"age"</span> : &#123;</span><br><span class="line">				<span class="string">"$gt"</span> : <span class="number">5</span></span><br><span class="line">			&#125;</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"winningPlan"</span> : &#123;</span><br><span class="line">			<span class="string">"stage"</span> : <span class="string">"COLLSCAN"</span>,</span><br><span class="line">			<span class="string">"filter"</span> : &#123;</span><br><span class="line">				<span class="string">"age"</span> : &#123;</span><br><span class="line">					<span class="string">"$gt"</span> : <span class="number">5</span></span><br><span class="line">				&#125;</span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"direction"</span> : <span class="string">"forward"</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"rejectedPlans"</span> : [ ]</span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"serverInfo"</span> : &#123;</span><br><span class="line">		<span class="string">"host"</span> : <span class="string">"2dd4d04418b1"</span>,</span><br><span class="line">		<span class="string">"port"</span> : <span class="number">27017</span>,</span><br><span class="line">		<span class="string">"version"</span> : <span class="string">"3.6.0"</span>,</span><br><span class="line">		<span class="string">"gitVersion"</span> : <span class="string">"a57d8e71e6998a2d0afde7edc11bd23e5661c915"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="重建索引"><a href="#重建索引" class="headerlink" title="重建索引"></a>重建索引</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.reIndex();</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"nIndexesWas"</span> : <span class="number">2</span>,</span><br><span class="line">	<span class="string">"nIndexes"</span> : <span class="number">2</span>,</span><br><span class="line">	<span class="string">"indexes"</span> : [</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"key"</span> : &#123;</span><br><span class="line">				<span class="string">"_id"</span> : <span class="number">1</span></span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"name"</span> : <span class="string">"_id_"</span>,</span><br><span class="line">			<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">		&#125;,</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"unique"</span> : <span class="literal">true</span>,</span><br><span class="line">			<span class="string">"key"</span> : &#123;</span><br><span class="line">				<span class="string">"name"</span> : <span class="number">1</span></span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"name"</span> : <span class="string">"name_1"</span>,</span><br><span class="line">			<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">		&#125;</span><br><span class="line">	],</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="组合索引"><a href="#组合索引" class="headerlink" title="组合索引"></a>组合索引</h2><p><a href="https://docs.mongodb.com/manual/indexes/index.html#compound-index" target="_blank" rel="noopener">https://docs.mongodb.com/manual/indexes/index.html#compound-index</a></p>
<p><img src="https://docs.mongodb.com/manual/_images/index-compound-key.bakedsvg.svg" alt=""></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.myindex.createIndex(&#123;<span class="attr">age</span>:<span class="number">1</span>, <span class="attr">name</span>:<span class="number">1</span>&#125;, &#123;<span class="attr">name</span>:<span class="string">'myNameAndAge'</span>&#125;)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"createdCollectionAutomatically"</span> : <span class="literal">false</span>,</span><br><span class="line">	<span class="string">"numIndexesBefore"</span> : <span class="number">2</span>,</span><br><span class="line">	<span class="string">"numIndexesAfter"</span> : <span class="number">3</span>,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">&gt; db.myindex.getIndexes();</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"_id"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"_id_"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"unique"</span> : <span class="literal">true</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"name"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"name_1"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"v"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"key"</span> : &#123;</span><br><span class="line">			<span class="string">"age"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"name"</span> : <span class="number">1</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"name"</span> : <span class="string">"myNameAndAge"</span>,</span><br><span class="line">		<span class="string">"ns"</span> : <span class="string">"test.myindex"</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h1 id="查询优化器"><a href="#查询优化器" class="headerlink" title="查询优化器"></a>查询优化器</h1><p>mysql里面有一个慢查询日志，记录了查询比较慢的一些查询，可以让开发人员分析。</p>
<p>mongodb也提供了profiling，它默认是没有开启的，需要手动开启，0表示没有开启。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.getProfilingLevel();</span><br><span class="line"><span class="number">0</span></span><br></pre></td></tr></table></figure>
<p>这个值为1的时候，大于100毫秒的的查询会被记录，如果为2，所有的查询记录都会被记录。</p>
<p>数据准备:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.post.save(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>, <span class="attr">age</span>:<span class="number">20</span>&#125;)</span><br><span class="line">&gt; db.post.save(&#123;<span class="attr">name</span>:<span class="string">'lisi'</span>, <span class="attr">age</span>:<span class="number">21</span>&#125;)</span><br><span class="line">&gt; db.post.save(&#123;<span class="attr">name</span>:<span class="string">'wangwu'</span>, <span class="attr">age</span>:<span class="number">22</span>&#125;)</span><br></pre></td></tr></table></figure>
<p>改变profilingLevel，开启profiling，为了演示，设置成2，记录所有的查询。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.setProfilingLevel(<span class="number">2</span>);</span><br><span class="line">&#123; <span class="string">"was"</span> : <span class="number">0</span>, <span class="string">"slowms"</span> : <span class="number">100</span>, <span class="string">"sampleRate"</span> : <span class="number">1</span>, <span class="string">"ok"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
<p>可以看到多了一个集合，实际上查询记录就会被记录到system.profile集合当中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; show collections;</span><br><span class="line">post</span><br><span class="line">system.profile</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.post.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51cef5a893e40faf1670cf"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51cf00a893e40faf1670d0"</span>), <span class="string">"name"</span> : <span class="string">"lisi"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a51cf0aa893e40faf1670d1"</span>), <span class="string">"name"</span> : <span class="string">"wangwu"</span>, <span class="string">"age"</span> : <span class="number">22</span> &#125;</span><br><span class="line">&gt; db.system.profile.find().pretty();</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"op"</span> : <span class="string">"query"</span>,</span><br><span class="line">	<span class="string">"ns"</span> : <span class="string">"mytest.post"</span>,</span><br><span class="line">	<span class="string">"command"</span> : &#123;</span><br><span class="line">		<span class="string">"find"</span> : <span class="string">"post"</span>,</span><br><span class="line">		<span class="string">"filter"</span> : &#123;</span><br><span class="line">			</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"$db"</span> : <span class="string">"mytest"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"keysExamined"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"docsExamined"</span> : <span class="number">3</span>,</span><br><span class="line">	<span class="string">"cursorExhausted"</span> : <span class="literal">true</span>,</span><br><span class="line">	<span class="string">"numYield"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"locks"</span> : &#123;</span><br><span class="line">		<span class="string">"Global"</span> : &#123;</span><br><span class="line">			<span class="string">"acquireCount"</span> : &#123;</span><br><span class="line">				<span class="string">"r"</span> : NumberLong(<span class="number">2</span>)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"Database"</span> : &#123;</span><br><span class="line">			<span class="string">"acquireCount"</span> : &#123;</span><br><span class="line">				<span class="string">"r"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"Collection"</span> : &#123;</span><br><span class="line">			<span class="string">"acquireCount"</span> : &#123;</span><br><span class="line">				<span class="string">"r"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"nreturned"</span> : <span class="number">3</span>,</span><br><span class="line">	<span class="string">"responseLength"</span> : <span class="number">249</span>,</span><br><span class="line">	<span class="string">"protocol"</span> : <span class="string">"op_msg"</span>,</span><br><span class="line">	<span class="string">"millis"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"planSummary"</span> : <span class="string">"COLLSCAN"</span>,</span><br><span class="line">	<span class="string">"execStats"</span> : &#123;</span><br><span class="line">		<span class="string">"stage"</span> : <span class="string">"COLLSCAN"</span>,</span><br><span class="line">		<span class="string">"nReturned"</span> : <span class="number">3</span>,</span><br><span class="line">		<span class="string">"executionTimeMillisEstimate"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"works"</span> : <span class="number">5</span>,</span><br><span class="line">		<span class="string">"advanced"</span> : <span class="number">3</span>,</span><br><span class="line">		<span class="string">"needTime"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"needYield"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"saveState"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"restoreState"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"isEOF"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"invalidates"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"direction"</span> : <span class="string">"forward"</span>,</span><br><span class="line">		<span class="string">"docsExamined"</span> : <span class="number">3</span></span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"ts"</span> : ISODate(<span class="string">"2018-01-07T07:58:31.109Z"</span>),</span><br><span class="line">	<span class="string">"client"</span> : <span class="string">"172.17.0.1"</span>,</span><br><span class="line">	<span class="string">"appName"</span> : <span class="string">"MongoDB Shell"</span>,</span><br><span class="line">	<span class="string">"allUsers"</span> : [ ],</span><br><span class="line">	<span class="string">"user"</span> : <span class="string">""</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>profile的内容有点多，docsExamined扫描过3个文档，nreturned表示返回了3个文档。接着给name创建一个索引，再查询一次。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line">db.post.createIndex(&#123;<span class="attr">name</span>:<span class="number">1</span>&#125;)</span><br><span class="line">db.post.find(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>&#125;);</span><br><span class="line">db.system.profile.find().pretty()</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"op"</span> : <span class="string">"query"</span>,</span><br><span class="line">	<span class="string">"ns"</span> : <span class="string">"mytest.post"</span>,</span><br><span class="line">	<span class="string">"command"</span> : &#123;</span><br><span class="line">		<span class="string">"find"</span> : <span class="string">"post"</span>,</span><br><span class="line">		<span class="string">"filter"</span> : &#123;</span><br><span class="line">			<span class="string">"name"</span> : <span class="string">"zhangsan"</span></span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"$db"</span> : <span class="string">"mytest"</span></span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"keysExamined"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"docsExamined"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"cursorExhausted"</span> : <span class="literal">true</span>,</span><br><span class="line">	<span class="string">"numYield"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"locks"</span> : &#123;</span><br><span class="line">		<span class="string">"Global"</span> : &#123;</span><br><span class="line">			<span class="string">"acquireCount"</span> : &#123;</span><br><span class="line">				<span class="string">"r"</span> : NumberLong(<span class="number">2</span>)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"Database"</span> : &#123;</span><br><span class="line">			<span class="string">"acquireCount"</span> : &#123;</span><br><span class="line">				<span class="string">"r"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;,</span><br><span class="line">		<span class="string">"Collection"</span> : &#123;</span><br><span class="line">			<span class="string">"acquireCount"</span> : &#123;</span><br><span class="line">				<span class="string">"r"</span> : NumberLong(<span class="number">1</span>)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"nreturned"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"responseLength"</span> : <span class="number">141</span>,</span><br><span class="line">	<span class="string">"protocol"</span> : <span class="string">"op_msg"</span>,</span><br><span class="line">	<span class="string">"millis"</span> : <span class="number">4</span>,</span><br><span class="line">	<span class="string">"planSummary"</span> : <span class="string">"IXSCAN &#123; name: 1 &#125;"</span>,</span><br><span class="line">	<span class="string">"execStats"</span> : &#123;</span><br><span class="line">		<span class="string">"stage"</span> : <span class="string">"FETCH"</span>,</span><br><span class="line">		<span class="string">"nReturned"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"executionTimeMillisEstimate"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"works"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"advanced"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"needTime"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"needYield"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"saveState"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"restoreState"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"isEOF"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"invalidates"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"docsExamined"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"alreadyHasObj"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"inputStage"</span> : &#123;</span><br><span class="line">			<span class="string">"stage"</span> : <span class="string">"IXSCAN"</span>,</span><br><span class="line">			<span class="string">"nReturned"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"executionTimeMillisEstimate"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"works"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"advanced"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"needTime"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"needYield"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"saveState"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"restoreState"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"isEOF"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"invalidates"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"keyPattern"</span> : &#123;</span><br><span class="line">				<span class="string">"name"</span> : <span class="number">1</span></span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"indexName"</span> : <span class="string">"name_1"</span>,</span><br><span class="line">			<span class="string">"isMultiKey"</span> : <span class="literal">false</span>,</span><br><span class="line">			<span class="string">"multiKeyPaths"</span> : &#123;</span><br><span class="line">				<span class="string">"name"</span> : [ ]</span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"isUnique"</span> : <span class="literal">false</span>,</span><br><span class="line">			<span class="string">"isSparse"</span> : <span class="literal">false</span>,</span><br><span class="line">			<span class="string">"isPartial"</span> : <span class="literal">false</span>,</span><br><span class="line">			<span class="string">"indexVersion"</span> : <span class="number">2</span>,</span><br><span class="line">			<span class="string">"direction"</span> : <span class="string">"forward"</span>,</span><br><span class="line">			<span class="string">"indexBounds"</span> : &#123;</span><br><span class="line">				<span class="string">"name"</span> : [</span><br><span class="line">					<span class="string">"[\"zhangsan\", \"zhangsan\"]"</span></span><br><span class="line">				]</span><br><span class="line">			&#125;,</span><br><span class="line">			<span class="string">"keysExamined"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"seeks"</span> : <span class="number">1</span>,</span><br><span class="line">			<span class="string">"dupsTested"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"dupsDropped"</span> : <span class="number">0</span>,</span><br><span class="line">			<span class="string">"seenInvalidated"</span> : <span class="number">0</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"ts"</span> : ISODate(<span class="string">"2018-01-07T08:04:05.695Z"</span>),</span><br><span class="line">	<span class="string">"client"</span> : <span class="string">"172.17.0.1"</span>,</span><br><span class="line">	<span class="string">"appName"</span> : <span class="string">"MongoDB Shell"</span>,</span><br><span class="line">	<span class="string">"allUsers"</span> : [ ],</span><br><span class="line">	<span class="string">"user"</span> : <span class="string">""</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因为post的name字段是加了索引的，所以这次的查询记录，indexName显示用到的索引名称，keysExamined为1，表示扫描了1条索引，这次docsExamined为1，只扫描了一条文档。</p>
<p>索引和查询计划就说到这里，下面的文章，讲解最后一部分，也就是副本集。</p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mongo/" rel="tag"># Mongo</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/01/mongo3/" rel="next" title="MongoDB3-三种聚合操作详解">
                <i class="fa fa-chevron-left"></i> MongoDB3-三种聚合操作详解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/07/mongo5/" rel="prev" title="MongoDB5-副本集">
                MongoDB5-副本集 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#GridFS"><span class="nav-number">1.</span> <span class="nav-text">GridFS</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#mongofiles"><span class="nav-number">1.1.</span> <span class="nav-text">mongofiles</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#上传"><span class="nav-number">1.1.1.</span> <span class="nav-text">上传</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#搜索"><span class="nav-number">1.1.2.</span> <span class="nav-text">搜索</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除"><span class="nav-number">1.1.3.</span> <span class="nav-text">删除</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Capped-Collections"><span class="nav-number">2.</span> <span class="nav-text">Capped Collections</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建"><span class="nav-number">2.1.</span> <span class="nav-text">创建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查询"><span class="nav-number">2.2.</span> <span class="nav-text">查询</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#索引与查询计划"><span class="nav-number">3.</span> <span class="nav-text">索引与查询计划</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建索引"><span class="nav-number">3.1.</span> <span class="nav-text">创建索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除索引"><span class="nav-number">3.2.</span> <span class="nav-text">删除索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#唯一索引"><span class="nav-number">3.3.</span> <span class="nav-text">唯一索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查询计划"><span class="nav-number">3.4.</span> <span class="nav-text">查询计划</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重建索引"><span class="nav-number">3.5.</span> <span class="nav-text">重建索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#组合索引"><span class="nav-number">3.6.</span> <span class="nav-text">组合索引</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#查询优化器"><span class="nav-number">4.</span> <span class="nav-text">查询优化器</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
